<?php
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/util.php';
set_time_limit(60*60);
ini_set('memory_limit', '512M');

$g_start = microtime(true);

if (count($argv) != 3)
{
	echo "Usage: php unsub [Site ID] [CSV File Name]\n";
	exit;
}
$dbconn = Connection::getInstance();

$filename = $argv[2];
$file = fopen($filename, 'r');
if (!$file)
{
	echo "Could not open file: ". $filename . "\n";
	exit;
}
if ($file)
{
	$c = 0;
	while ($line = fgets($file))
	{
		if($user = getUser($dbconn, trim($line), $argv[1])){
			//addToSubUser_AIB($dbconn, $user['id']);
			//addToSubUser_RG($dbconn, $user['id']);
		
			$ret = unsub($dbconn, trim($line), $argv[1]);
			$c ++;
			echo $c . "\t". trim($line). "\t". (($ret>0)?'*':'') ."\n";
		}
	}
	fclose($file);
}

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";

function unsub($db, $email, $site)
{
	$sql = "update users set unsub=1 where email=? and site_id=?";
	try
	{
		return $db->execute($sql, array($email, $site));
	}
	catch (Exception $e)
	{
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
function getUser($db, $email, $site)
{
	$sql = " select * from users where email=? and site_id=? and unsub=0 ";
	try
	{
//		$ret = count($db->query($sql, array($email, $site)));
//		return $ret;
		$result = $db->query($sql, array($email, $site));
		if(count($result) > 0){
			return $result[0];
		}
		return false;
	}
	catch (Exception $e)
	{
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}





function addToSubUser_AIB($db, $uid)
{
	$sql = " INSERT INTO allinbox_subscriber SET user_id=? , status='tounsub'";
	try{
		return $db->execute($sql, array( $uid ));
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function addToSubUser_RG($db, $uid)
{
	$sql = " INSERT INTO resultsgeneration_subscriber SET user_id=?, status='tounsub' ";
	try{
		return $db->execute($sql, array( $uid ));
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}
?>